package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/fwhezfwhez/errorx"
)

type Equipment struct {
	Id         string `orm:"column(id);pk" json:"id" form:"id"`
	UserId     string `orm:"column(user_id)" json:"user_id" form:"user_id"`
	Name       string `orm:"column(name)" json:"name" form:"name"`
	Sta        string `orm:"column(sta)" json:"sta" form:"sta"`
	SceneId    string `orm:"column(scene_id)" json:"scene_id" form:"scene_id"`
	Type       int64  `orm:"column(type)" json:"type" form:"type"`
	Password   string `orm:"column(password)" json:"-" form:"password"`
	CreateTime int64  `orm:"column(create_time)" json:"create_time" form:"create_time"`
	Version    string `orm:"column(version)" json:"version"`
}

func init() {
	orm.RegisterModel(new(User))
}

func (m *Equipment) TableName() string {
	return "equipment"
}

// 根据id获取设备
func GetEquipmentById(id string) (*Equipment, error) {
	data := &Equipment{Id: id}
	if err := orm.NewOrm().Read(data); err != nil {
		if err == orm.ErrNoRows {
			return nil, nil
		}
		return nil, errorx.New(err)
	}
	return data, nil
}

// 获取设备列表
// @return lists 设备列表
// @return count 符合条件的总数据量
// @return err error
func GetEquipmentLists(wheres map[string]interface{}, page int64) (lists []*Equipment, count int64, err error) {
	qs := orm.NewOrm().QueryTable(new(Equipment).TableName())

	if len(wheres) > 0 {
		for name, value := range wheres {
			qs = qs.Filter(name, value)
		}
	}

	if page < 1 {
		page = 1
	}

	// 符合条件的总条数
	count, err = qs.Count()
	if err != nil {
		return nil, 0, errorx.New(err)
	}
	if count == 0 {
		return nil, 0, nil
	}

	// 每页限制数量
	offset := beego.AppConfig.DefaultInt64("page_offset_number", 20)
	start := (page - 1) * offset
	num, err := qs.Limit(start).Offset(offset).All(&lists)
	if err != nil {
		return nil, 0, errorx.New(err)
	}
	if num == 0 {
		return nil, 0, nil
	}

	return lists, count, nil
}
